package com.game.nonperfomers;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;

import com.game.base.NonPerformer;
import com.module.itemeditor.CfgItem;
import com.module.itemeditor.IntegerProperty;
import com.module.itemeditor.StringProperty;

/**
 * 物品
 * @author chzcb
 * @email chzcb2008@gmail.com
 * @date 2011-8-31
 *
 */
public class Item extends NonPerformer{

	private static final long serialVersionUID = -6241726997506260539L;
	
	//所对应模型
	public int cfg_id;
	
	public String name;
	
	//类型
	public String type;
	
	/**
	 * 把CfgItem属性表里面的所有属性都赋值到当前对象，如果当前对象没有找到CfgItem里面的属性名称，就会报错误日志，但不影响整体
	 */
	protected void initFields(){
		CfgItem cfg = CfgItem.getCfgItem(cfg_id);
		if(cfg==null)
			return;
		Field field = null;
		for(Object p : cfg.attrs){
			if(p instanceof IntegerProperty){
				IntegerProperty ip = (IntegerProperty)p;
				try {
					field = this.getClass().getField(ip.getName());
					field.set(this, ip.getValue());	
				} catch (Exception e) {
					try {
						String methodname = ip.getName();
						methodname = methodname.replaceFirst(methodname.substring(0, 1),methodname.substring(0, 1).toUpperCase());
						methodname = "set"+methodname;
						Method method = this.getClass().getMethod(methodname, Integer.class);
						method.invoke(this, ip.getValue());
					} catch (Exception e2) {
						Logger.getLogger("CfgItem").error("[CfgItem:"+cfg_id+"]no use Integer attr:"+p);
						continue;
					}
				}
			}
			else if(p instanceof StringProperty){
				StringProperty sp = (StringProperty)p;
				try {
					field = this.getClass().getField(sp.getName());
					field.set(this, sp.getValue());
				} catch (Exception e) {
					try {
						String methodname = sp.getName();
						methodname = methodname.replaceFirst(methodname.substring(0, 1),methodname.substring(0, 1).toUpperCase());
						methodname = "set"+methodname;
						Method method = this.getClass().getMethod(methodname, String.class);
						method.invoke(this, sp.getValue());
					} catch (Exception e2) {
						Logger.getLogger("CfgItem").error("[CfgItem:"+cfg_id+"]no use String attr:"+p);
						continue;
					}
				}
			}			
		}
	}
	
	public void initInstance(){
		initFields();
	}
}
